<?php


namespace Modules\Pmcsignage\Http\Repositories;

use App\Services\KingDeeService;
use App\Services\UnitService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Modules\Inventory\Repository\InventoryOrderRepository;
use Modules\Purchasing\Models\Provisional;
use Modules\Purchasing\Models\Provisionalschedule;
use Illuminate\Support\Facades\DB;
use Catch\Exceptions\FailedException;
use Modules\Base\Service\BoxService;
use Modules\Purchasing\Models\Supplier;
use Modules\Purchasing\Models\Supplierschedule;
use Modules\Purchasing\Models\Purchaseorder;
use Modules\Purchasing\Models\Purchaseorderschedule;
use Modules\Warehouse\Models\Storagelocation;
use Modules\Purchasing\Models\Inspectionlist;
use Modules\Purchasing\Models\Inspectionlistcheck;
use extend\services\warehouse\{warehouseService};//引入自定义类
use Modules\Intelligent\Http\Repositories\InspectionlistReget;
use Modules\Intelligent\Models\Otherstorage;
use Modules\Intelligent\Models\Otherstorageschedule;
use Modules\Intelligent\Models\Lotbinding;
use Modules\Takestock\Models\InventoryOrderDetailschedule;
use Modules\Inventory\Models\InventoryOrderDetail;
use Modules\Intelligent\Models\Otheroutboundfrom;
use Modules\Intelligent\Models\OtheroutboundfromSchedule;
use App\Enums\InvTransDocType;
use App\Services\InventoryService;
use App\Enums\InventoryOrderStatus;
use Modules\Production\Models\ProductionOrder;
use Modules\Production\Models\ProductionOrderDetail;
use Modules\Pmcsignage\Models\ProductionTheweekplan;
use Modules\Salesmanagement\Models\Salesout;
use Modules\Salesmanagement\Models\SalesoutAttached;
use extend\services\nailin\NewdemandService;//使用金蝶接口

class OrderstodayReget
{


    /*
    请求金蝶获取字段
    */
    public static function tablelist($data){
     
     
             
        $kingDeeService = new NewdemandService();
        //字段
        
        $fields   =  ['FBillNo','FDate','FQty','FDocumentStatus','FSaleOrderEntry_FSEQ','FMaterialId.FNUMBER','FMaterialId.FNAME'];

        
        // $where  = "FDate='C' AND FFORBIDSTATUS='A'";
        
        $where  = "FDate='{$data['FDate']}'";
        $postJson   = [
            'FormId'        => 'SAL_SaleOrder',
            'FieldKeys'     => implode(',',$fields),
            'FilterString'  => $where,
            //'FilterString'  => [],
            'OrderString'   => '',
            'TopRowCount'   => 0,
            'StartRow'      => 0,
            'Limit'         => 0,
            'SubSystemId'   => '',
        ];
        
        $postJson = $kingDeeService->create_postdata([json_encode($postJson)]);
        $reslut = $kingDeeService->ExecuteBillQuery($kingDeeService->cloudUrl, $postJson);
     
        if(empty($reslut)) throw new \Exception('接口返回为空');
        $reslut = json_decode($reslut,true);
        if(!isset($reslut[0]) || empty($reslut[0])) return [];
        // p(self::listToValue($reslut,$fields));
        return self::listToValue($reslut,$fields);
        exit;

        
        
    }
    
    
   
    public static function listtable($data = [])
    {
        return self::getBuildertable($data)->paginate($data['limit'] ?? 100);
    }


    public static function getBuildertable(array $data = []): Builder
    {
       

        $builder = SalesoutAttached::query();
        if (isset($data['FDate'])) {
            $str = strtotime($data['FDate'].' 00:00');
            $end = strtotime($data['FDate'].' 23:59');
            $builder->where('created_at','>=' , $str);
            $builder->where('created_at','<=' , $end);
        }
        
        if (isset($data['fbillno'])) {
           $fbillno = Salesout::select('fbillno','id')->where('fbillno', 'like', "%{$data['fbillno']}%")->get()->toArray();
             $fmaterial_fbillno = [];
            foreach($fbillno as $k=>$v){
                $fmaterial_fbillno[] = $v['id'];
            }
            $fmaterial_fbillno = array_unique($fmaterial_fbillno);
            
            $builder->whereIn('salesout_id',$fmaterial_fbillno);
        }
        
         if (isset($data['fmaterialid'])) {
              $builder->where('fmaterialid', 'like', "%{$data['fmaterialid']}%");
        }
         if (isset($data['fmaterialname'])) {
              $builder->where('fmaterialname', 'like', "%{$data['fmaterialname']}%");
        }
        
        
        
        $builder->orderBy('id', 'desc');
        $builder->get()->toArray();
        return $builder;
  
    }

    /*
    表头计算
    */
    public static function tablecont($data)
    {
        
        $str = strtotime($data['FDate'].' 00:00');
        $end = strtotime($data['FDate'].' 23:59');
        //完成出库单量
        $Salesout = Salesout::query()
        ->select('id')
        ->where('writestate',1)
        ->where('created_at','>=' , $str)
        ->where('created_at','<=' , $end)
        ->get()
        ->toArray();
        $cunt = 0;
        $cunt_fty = 0;
        foreach($Salesout as $k=>$v){
            //完成出库数量
            $fqty = SalesoutAttached::query()
            ->select(DB::raw('SUM(fqty) as fqty'))
            ->where('salesout_id',$v['id'])
            ->groupby(['salesout_id'])
            ->first();
            $cunt_fty +=$fqty['fqty'];
            $cunt ++;
        }
        
         //待出库单量
         $Salesout_two = Salesout::query()
         ->select('id')
         ->where('writestate',0)
         ->where('created_at','>=' , $str)
         ->where('created_at','<=' , $end)
         ->get()
         ->toArray();
         $cunt_two = 0;
         $cunt_fty_two = 0;
    
         foreach($Salesout_two as $k=>$v){
             //待出库数量
             $fqty_two = SalesoutAttached::query()
             ->select(DB::raw('SUM(fqty) as fqty'))
             ->where('salesout_id',$v['id'])
             ->groupby(['salesout_id'])
             ->first();
            
             $cunt_fty_two +=$fqty_two['fqty'];
             $cunt_two ++;
         }
    
        return [
            'created_at'=>$data['FDate'],
            'complete_order'=>$cunt,
            'complete_quantity'=>$cunt_fty,
            'released_order'=>$cunt_two,
            'released_quantity'=>$cunt_fty_two,
            'other_quantity'=>self::othercunt($data),
        ];
  
    }

    /*
    金蝶-其他出库待审单
    */
    public static function othercunt($data){
             
        $kingDeeService = new NewdemandService();
        //字段
     
        $fields   =  ['FDocumentStatus','FDate'];
        $where = "FDocumentStatus='B' AND FDate='{$data['FDate']}'";
        
        $postJson   = [
            'FormId'        => 'STK_MisDelivery',
            'FieldKeys'     => implode(',',$fields),
            'FilterString'  => $where,
            //'FilterString'  => [],
            'OrderString'   => '',
            'TopRowCount'   => 0,
            'StartRow'      => 0,
            'Limit'         => 0,
            'SubSystemId'   => '',
        ];
        
        $postJson = $kingDeeService->create_postdata([json_encode($postJson)]);
        $reslut = $kingDeeService->ExecuteBillQuery($kingDeeService->cloudUrl, $postJson);
     
        if(empty($reslut)) throw new \Exception('接口返回为空');
        $reslut = json_decode($reslut,true);
       
        $cunt = self::listToValue($reslut,$fields);
        
        if(!empty($cunt)){
            $cunt = count($cunt);
        }else{
            $cunt = 0;
        }

        return $cunt;
        exit;
       
        
        
        
    }
    
    /**
     * 列表数据转键值对
     * @param $list
     * @param $fields
     * @return array
     */
    public static function listToValue($list,$fields){
        $newList = [];
        foreach ($list as $key => $val){
            foreach ($val as $itemKey => $itemVal){
                $newList[$key][$fields[$itemKey]] = $itemVal;
            }
        }
        return $newList;
        
    }


   





}
